﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class GeoTiffOverlapProcessor
    {
        public static void ProcessOverlappedGeoTiffs(
        string[] inputPaths, string outputDir,
        int tileSize = 512, bool overwrite = false)
        {
            // 步骤1: 计算所有文件的公共重叠区域
            Envelope commonEnvelope = CalculateCommonEnvelope(inputPaths);

            // 步骤2: 创建统一切片网格
            TileGrid unifiedGrid = CreateUnifiedGrid(commonEnvelope, tileSize);

            // 步骤3: 为每个文件处理切片
            for (int i = 0; i < inputPaths.Length; i++)
            {
                string typeId = GetTypeIdentifier(inputPaths[i]);
                ProcessSingleFile(inputPaths[i], outputDir, unifiedGrid,
                                 typeId, tileSize, overwrite);
            }
        }

        private static Envelope CalculateCommonEnvelope(string[] paths)
        {
            Envelope commonEnv = null;

            foreach (var path in paths)
            {
                using (Dataset ds = Gdal.Open(path, Access.GA_ReadOnly))
                {
                    double[] gt = new double[6];
                    ds.GetGeoTransform(gt);

                    // 计算当前文件的边界
                    double minX = gt[0];
                    double maxY = gt[3];
                    double maxX = minX + ds.RasterXSize * gt[1];
                    double minY = maxY + ds.RasterYSize * gt[5];

                    var env = new Envelope(minX, maxX, minY, maxY);

                    // 计算交集
                    commonEnv = (commonEnv == null) ? env : commonEnv.Intersection(env);
                }
            }
            return commonEnv;
        }

    }
}
